#include "ReturnBuilder.h"

 
#include "ScriptCompiler/ScriptFileContext.h"
#include "ScriptCompiler/AST/ReturnNode.h"
#include "ScriptCompiler/ASTBuilder/ExpressionBuilder.h"

CReturnBuilder::CReturnBuilder(std::shared_ptr<CScriptFileContext> InContext)
{
    Context = InContext;
    Result = std::make_shared<CReturnNode>(InContext);

}

bool CReturnBuilder::ReadCurentToken()
{
    //read 'return'
    {
        auto Token = Context->GetCurrentToken();
        if (Token->Type != EScriptTokenType::Return)
        {
            Context->RaiseError(10088,Token, U"Expect 'return' here");
            return false;
        }
        Result->Return = Token;
        Context->CurrentTokenIndex++;
    }

    //check is current token is ';'
    auto Semicolon=Context->GetCurrentToken();
    if (Semicolon->Type == EScriptTokenType::Semicolon)
    {
        //skip ';'
        Context->CurrentTokenIndex++;
        return true;
    }

    //find ';'
    auto SemiColonIndex = FindNextToken(EScriptTokenType::Semicolon, Context);
    if (!SemiColonIndex.HasValue())
    {
        Context->RaiseError(10089,Context->GetCurrentToken(), U"Expect ';' at end of return-statement");
        return false;
    }

    {
        auto SentenceBuilder = std::make_shared<CExpressionBuilder>(Context, SemiColonIndex.GetValue());
        if (!SentenceBuilder->ReadCurentToken())
        {
            return false;
        }

        Result->Value = SentenceBuilder->Result;
    }

    //skip ';'
    assert(Context->GetCurrentToken()->Type == EScriptTokenType::Semicolon);
    Context->CurrentTokenIndex++;

    return true;
}
